package com.cn.my.newapp;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.jetbrains.annotations.Contract;

public class PagckManager {

    private PagckManager(){}

    public static class VersionInfo{
        public int versionCode;
        public String versionName;

        public VersionInfo(int versionCode, String versionName) {
            this.versionCode = versionCode;
            this.versionName = versionName;
        }

        public int getVersionCode() {
            return versionCode;
        }

        public VersionInfo setVersionCode(int versionCode) {
            this.versionCode = versionCode;
            return this;
        }

        public String getVersionName() {
            return versionName;
        }

        public VersionInfo setVersionName(String versionName) {
            this.versionName = versionName;
            return this;
        }
    }

    @NonNull
    @Contract("_ -> new")
    public static VersionInfo getVersion(Context context){
            // 获取PackageManager实例
            PackageManager packageManager = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packageInfo = null;
            try {
              packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
              throw new RuntimeException(e);
            }
        // 版本号
            int versionCode = packageInfo.versionCode;
            // 版本名
            String versionName = packageInfo.versionName;
            // 打印版本信息
            Log.d("VersionInfo", "Version Code: " + versionCode + ", Version Name: " + versionName);
            return new VersionInfo(versionCode,versionName);
    }
}
